package com.fch.sdlibrary;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.fch.sdlibrary.entity.BaseResponse;
import com.fch.sdlibrary.entity.User;
import com.fch.sdlibrary.global.MyGlobal;
import com.fch.sdlibrary.util.TokenInterceptor;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    private EditText username, password;
    private Button loginButton;
    private BaseResponse baseResponse;
    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        init();
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String usern = username.getText().toString();
                String pasw = password.getText().toString();
                if ("".equals(usern) || "".equals(pasw))
                    return;
                login(usern, pasw);
            }

            private void login(String usern, String pasw) {
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(3, TimeUnit.SECONDS)
                        .build();//创建Http客户端
                RequestBody formBody = new FormBody.Builder()
                        .add("username", usern)
                        .add("password", pasw)
                        .build();
                Request request = new Request.Builder()
                        .url(MyGlobal.PATH + "login")//***.***.**.***为本机IP，xxxx为端口，/  /  为访问的接口后缀
                        .post(formBody)
                        .build();//创建Http请求
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //请求失败的处理
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // 更新UI的操作
                                Toast.makeText(LoginActivity.this, "链接失败", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //请求成功返回结果
                        //如果希望返回的是字符串
                        final String responseData = response.body().string();
                        baseResponse = new BaseResponse<User>();
                        Type type = new TypeToken<BaseResponse<User>>() {
                        }.getType();
                        baseResponse = gson.fromJson(responseData, type);
                        if (baseResponse.getCode() == 0){
                            SharedPreferences userInfo = getSharedPreferences("data", MODE_PRIVATE);
                            SharedPreferences.Editor editor = userInfo.edit();//获取Editor
                            editor.putString("user", gson.toJson(baseResponse.getData()));
                            editor.putString("token", response.header("token"));
                            editor.apply();//提交修改
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        }
                        else{
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    // 更新UI的操作
                                    Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });
            }
        });
    }

    private void init() {
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        loginButton = findViewById(R.id.login_button);
        username.setText("1000000016");
        password.setText("123456");
    }
}
